package net.neiquan.applibrary.wight;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.AppCompatEditText;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import net.neiquan.applibrary.R;

import org.haitao.common.utils.StringUtils;

/**
 * 模仿微信的@功能 整块删除 可编辑
 * Created by dds on 2017/10/25.
 * QQ: 710715508
 */

public class MsgEditText extends AppCompatEditText {
    private int itemPadding;

    public MsgEditText(Context context) {
        super(context);
        init();
    }

    public MsgEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MsgEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();

    }
    private void init() {
        itemPadding = dip2px(getContext(), 3);
    }

    private StringBuilder builder;

    /**
     * 添加一个块,在文字的后面添加
     *
     * @param showText 显示到界面的内容
     * @param userId   附加属性，比如用户id,邮件id之类的，如果不需要可以去除掉
     */
    public void addAtSpan(String maskText, String showText, String userId) {
        builder = new StringBuilder();
        if (!TextUtils.isEmpty(maskText)) {
            //已经添加了@
            if(TextUtils.equals("@",maskText)) {
                builder.append(maskText).append(showText).append(" ");
            }
        } else {
            builder.append(showText).append(" ");
        }
        int selection = getSelectionStart();
        getText().insert(getSelectionStart(), builder.toString());
        SpannableString sps = new SpannableString(getText());

//        int start = sps.length() - builder.toString().length() - (TextUtils.isEmpty(maskText) ? 1 : 0);
        int start = selection;
        int end =start + builder.toString().length() - (TextUtils.isEmpty(maskText) ? 1 : 0);
        makeSpan(sps, new UnSpanText(start, end, builder.toString()), userId,maskText);
        setText(sps);
        setSelection(end);
    }

//    public void addAtSpanString(String maskText, List<RelayUserList> lists) {
//        for(int i=0;i< lists.size();i++){
//            String showText = lists.get(i).getNickName();
//            String userId = lists.get(i).getId();
//            String comment = lists.get(i).getRelayComment();
//            if(!StringUtils.isEmpty(comment.split("//")[0])){
//                builder = new StringBuilder();
//                if (!TextUtils.isEmpty(maskText)) {
//                    //已经添加了@
//                    builder.append(maskText).append(showText).append(" ");
//                } else {
//                    builder.append(showText).append(" ");
//                }
//                getText().append("//");
//                getText().insert(getSelectionStart(), builder.toString());
//                SpannableString sps = new SpannableString(getText());
//                int start = sps.length() - builder.toString().length() - (TextUtils.isEmpty(maskText) ? 1 : 0);
//                int end = sps.length();
//                makeSpan(sps, new UnSpanText(start, end, builder.toString()), userId,maskText);
//                setText(sps);
//                setSelection(end);
//                modifyString(comment);
//            }
//        }
//        setSelection(0);
//    }

    public void modifyString(String ss){
        Log.e("String1-",ss);
        if(!StringUtils.isEmpty(ss)){
            String s = ss.split("//")[0];
            Log.e("String1",s);
            if(s.split("//").length > 0 && s.contains("</a>") && s.contains("androidIntent.")){
                if(s.split(" </a>").length>1){
                    String content = s.split(" </a>")[1];
                    content = content.split("//")[0];
                    s = s.split(" </a>")[0];
                    String userName = s.replaceAll("<a .*?>","");
                    userName = userName.replaceAll(" </a>","");
                    String userId = s.replaceAll("<a id='","");
                    userId = userId.split("' onclick=")[0];
                    Log.e("String",userName+":"+userId+":"+content);
                    getText().append(": ");
                    addAtSpan("",userName,userId);
                    setSelection(getText().length());
                    getText().append(content);
                }else {
                    getText().append(": ");
                    String content = s.split("<a id='")[0];
                    getText().append(content);
                    String userName = s.replaceAll("<a .*?>","").replaceFirst(content,"");
                    userName = userName.replaceAll(" </a>","");
                    String userId = s.replaceAll("<a id='","").replaceFirst(content,"");
                    userId = userId.split("' onclick=")[0];
                    Log.e("String",userName+":"+userId+":"+content);
                    addAtSpan("",userName,userId);
                    setSelection(getText().length());
                }
            }else {
                String content = s.split("//")[0];
                getText().append(":"+content);
            }
        }
    }

    //获取用户Id列表
    public String getUserIdString() {
        MyTextSpan[] spans = getText().getSpans(0, getText().length(), MyTextSpan.class);
        StringBuilder builder = new StringBuilder();
        for (MyTextSpan myTextSpan : spans) {
            String realText = getText().toString().substring(getText().getSpanStart(myTextSpan), getText().getSpanEnd(myTextSpan));
            String showText = myTextSpan.getShowText();
            if (realText.equals(showText)) {
                builder.append(myTextSpan.getUserId()).append(",");
            }
        }
        if (!TextUtils.isEmpty(builder.toString())) {
            builder.deleteCharAt(builder.length() - 1);
        }
        return builder.toString();
    }

    public String getMaskString() {
        MyTextSpan[] spans = getText().getSpans(0, getText().length(), MyTextSpan.class);
        StringBuilder builder = new StringBuilder();
        for (MyTextSpan myTextSpan : spans) {
            String realText = getText().toString().substring(getText().getSpanStart(myTextSpan), getText().getSpanEnd(myTextSpan));
            String showText = myTextSpan.getShowText();
            if (realText.equals(showText)) {
                builder.append(myTextSpan.getMaskText()).append(",");
            }
        }
        if (!TextUtils.isEmpty(builder.toString())) {
            builder.deleteCharAt(builder.length() - 1);
        }
        return builder.toString();
    }

    public String getUserNameString() {
        MyTextSpan[] spans = getText().getSpans(0, getText().length(), MyTextSpan.class);
        StringBuilder builder = new StringBuilder();
        for (MyTextSpan myTextSpan : spans) {
            String realText = getText().toString().substring(getText().getSpanStart(myTextSpan), getText().getSpanEnd(myTextSpan));
            String showText = myTextSpan.getShowText();
            if (realText.equals(showText)) {
                builder.append(myTextSpan.getShowText()).append(",");
            }
        }
        if (!TextUtils.isEmpty(builder.toString())) {
            builder.deleteCharAt(builder.length() - 1);
        }
        return builder.toString();
    }

    //生成一个需要整体删除的Span
    private void makeSpan(Spannable sps, UnSpanText unSpanText, String userId,String maskText) {
        View spanView = getSpanView(getContext(), unSpanText.returnText.toString(), getMeasuredWidth());
        BitmapDrawable bitmapDrawable = (BitmapDrawable) convertViewToDrawable(spanView);
        bitmapDrawable.setBounds(0, 0, bitmapDrawable.getIntrinsicWidth(), bitmapDrawable.getIntrinsicHeight());
        MyTextSpan what = new MyTextSpan(bitmapDrawable, unSpanText.returnText.toString(),userId,maskText);
        final int start = unSpanText.start;
        final int end = unSpanText.end;
        if (end > 0)
        sps.setSpan(what, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

//        MyTextSpan what = new MyTextSpan(unSpanText.returnText, userId);
//        int start = unSpanText.start;
//        int end = unSpanText.end;
//        sps.setSpan(what, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    public Drawable convertViewToDrawable(View view) {
        int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        view.measure(spec, spec);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        Bitmap b = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        c.translate(-view.getScrollX(), -view.getScrollY());
        view.draw(c);
        view.setDrawingCacheEnabled(true);
        Bitmap cacheBmp = view.getDrawingCache();
        Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
        cacheBmp.recycle();
        view.destroyDrawingCache();
        return new BitmapDrawable(viewBmp);
    }

    public View getSpanView(Context context, String text, int maxWidth) {
        Drawable drawable = getResources().getDrawable(R.drawable.a_j);// 找到资源图片
        // 这一步必须要做，否则不会显示。
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());// 设置图片宽高
        TextView view = new TextView(context);
//        view.setCompoundDrawables(drawable,null,null,null);
        view.setMaxWidth(maxWidth);
        view.setText(text);
        view.setEllipsize(TextUtils.TruncateAt.END);
        view.setSingleLine(true);
        //设置文字框背景色
//        view.setBackgroundResource(R.drawable.shape_corner_rectangle);
        //view.setBackgroundResource(R.drawable.shape_corner_rectangle);
        view.setTextSize(getTextSize());
        //设置文字颜色
        //view.setTextColor(getCurrentTextColor());
        view.setTextColor(Color.BLUE);
        FrameLayout frameLayout = new FrameLayout(context);
        frameLayout.setPadding(itemPadding, itemPadding, itemPadding, itemPadding);
        frameLayout.addView(view);
        return frameLayout;
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
        //向前删除一个字符，@后的内容必须大于一个字符，可以在后面加一个空格
        if (lengthBefore == 1 && lengthAfter == 0) {
            MyTextSpan[] spans = getText().getSpans(0, getText().length(), MyTextSpan.class);
            for (MyTextSpan myImageSpan : spans) {
                if (getText().getSpanEnd(myImageSpan) == start && !text.toString().endsWith(myImageSpan.getShowText())) {
                    getText().delete(getText().getSpanStart(myImageSpan), getText().getSpanEnd(myImageSpan));
                    break;
                }
            }
        }

    }

    public class MyTextSpan extends ImageSpan {
        private String showText;
        private String userId;
        private String maskText;

        public MyTextSpan(Drawable d, String showText, String userId,String maskText) {
            super(d);
            this.showText = showText;
            this.userId = userId;
            this.maskText = maskText;
        }


        public String getShowText() {
            return showText;
        }

        public String getUserId() {
            return userId;
        }

        public String getMaskText() {
            return maskText;
        }

        @Override
        public void updateMeasureState(TextPaint p) {

        }

        @Override
        public void updateDrawState(TextPaint tp) {

        }
    }

    private class UnSpanText {
        int start;
        int end;
        CharSequence returnText;

        UnSpanText(int start, int end, CharSequence returnText) {
            this.start = start;
            this.end = end;
            this.returnText = returnText;
        }
    }

    /**
     * dip转换px
     */
    public static int dip2px(Context context, int dip) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f);
    }

}
